package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class ReadWritePictureDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane root = new AnchorPane();

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setWidth(1000);
        primaryStage.setHeight(500);
        primaryStage.centerOnScreen();
        primaryStage.setTitle("系统托盘");
        primaryStage.show();

        Image image = new Image("images/1.png");
        int w = (int) image.getWidth();
        int h = (int) image.getHeight();
        // 读像素
        PixelReader pixelReader = image.getPixelReader();
        // 写像素
        WritableImage wi = new WritableImage(pixelReader, w, h);
        PixelWriter pixelWriter = wi.getPixelWriter();

        ImageView iv = new ImageView(image);

        Button b1 = new Button("还原");
        Button b2 = new Button("解析");

        HBox hBox = new HBox(20);
        hBox.getChildren().addAll(b1, b2);

        root.getChildren().addAll(iv, hBox);
        AnchorPane.setTopAnchor(iv, 100d);
        AnchorPane.setLeftAnchor(iv, 100d);

        AnchorPane.setTopAnchor(hBox, 50d);
        AnchorPane.setLeftAnchor(hBox, 100d);

        b1.setOnAction(event -> {
            iv.setImage(image);
        });

        b2.setOnAction(event -> {
            for (int i = 0; i < w; i++) {
                for (int j = 0; j < h; j++) {
                    Color color = pixelReader.getColor(i, j);

                    double opa = color.getOpacity();
                    int r = (int) (color.getRed() * 255);
                    int g = (int) (color.getGreen() * 255);
                    int b = (int) (color.getBlue() * 255);

                    if (r != 0 && b != 0 && g != 0) {
                        int temp_r = r + 150;
                        int temp_g = g + 150;
                        int temp_b = b + 150;

                        if (temp_r > 255) {
                            temp_r = 255;
                        }
                        if (temp_g > 255) {
                            temp_g = 255;
                        }
                        if (temp_b > 255) {
                            temp_b = 255;
                        }

                        Color temp = Color.rgb(temp_r, temp_g, temp_b);
                        pixelWriter.setColor(i, j, temp);
                    }
                }
            }

            iv.setImage(wi);
        });
    }
}
